﻿////////////////////////////////////////////////////////////////////////////////
// Source Copyright (C) J.Fan
// @author      J.Fan
// @date        2013-01-19
// @revision    Revision in Version Control System
// @remark      
////////////////////////////////////////////////////////////////////////////////

using System;

namespace JsonConverter.Converter
{
    /// <summary>
    /// Convert DateTime value to milliseconds from 1979-1-1
    /// so that Javascript can construct a Date object with it
    /// </summary>
    public class DateTimeMillisecondConverter: IPrimitiveConverter
    {
        public static readonly DateTime JavascriptStartDate
            = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        public string Convert(object value)
        {
            return ToJavaScriptMilliSeconds((DateTime) value).ToString();
        }

        public static long ToJavaScriptMilliSeconds(DateTime value)
        {
            return (long) (((DateTime) value).ToUniversalTime()
                - JavascriptStartDate).TotalMilliseconds;
        }
    }
}
